package com.phone.servlet;

import com.phone.ParameterCheck;
import com.phone.entity.Result;
import com.phone.entity.User;
import com.phone.entity.User2;
import com.phone.exception.ErrorCode;
import com.phone.exception.ErrorException;
import org.hibernate.Session;
import org.json.JSONObject;

import javax.servlet.annotation.WebServlet;

/**
 * Created by tisen on 2017/9/22.
 */
@WebServlet(name = "User", urlPatterns = "/user")
public class UserServlet extends SuperServlet {
    private static final String GET = "get";
    private static final String UPDATE = "update";

    private static final String ID = "id";

    @Override
    protected JSONObject Control(ParameterCheck check, Session session) throws Exception {
        JSONObject jsonObject = new JSONObject();

        String action = check.getParameterString(ACTION, false);
        switch (action) {
            case GET:
                jsonObject = get(check, session);
                break;
            case UPDATE:
                jsonObject = update(check, session);
                break;
            default:
                throw new ErrorException(ErrorCode.UN_DEFINED_ACTION);
        }

        return jsonObject;
    }

    private JSONObject update(ParameterCheck check, Session session) {
        return null;
    }

    private JSONObject get(ParameterCheck check, Session session) throws Exception {
        String id = check.getParameterString(ID, false);
        Result<User2> result = new Result<>();
        result.setResult(SUCCESS);
        result.setReason("get user successful");
        result.setObject(session.get(User2.class, id));
        return new JSONObject(result);
    }
}
